﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XCommon.Types;
using MySql.Data.MySqlClient;

namespace XDAL
{
    public class tbGroups : tbBase<tbGroups>
    {
        private const string SQL_SELECT = "SELECT * FROM tbgroups ORDER BY idesc DESC LIMIT 0,50";
        private const string SQL_INSERT = "INSERT INTO tbgroups(typename) VALUES(@typename);SELECT @@IDENTITY; ";
        private const string SQL_UPDATE = "UPDATE tbgroups SET typename=@typename WHERE typeid=@typeid ";
        private const string SQL_DELETE = "DELETE FROM tbphototype WHERE typeid=@typeid ";

        public List<Ps> Select()
        {
            return MySQL.MySqlHelper.ReadToList(MySQL.MySqlHelper.ExecuteReader(SQL_SELECT, null));
        }

        public bool Insert(List<Ps> list, ref string _errmsg)
        {
            return this.Operate(list, ref _errmsg, DataOperate.Insert);
        }

        public bool Update(List<Ps> list, ref string _errmsg)
        {
            return this.Operate(list, ref _errmsg, DataOperate.Update);
        }

        public bool Delete(List<Ps> list, ref string _errmsg)
        {
            return this.Operate(list, ref _errmsg, DataOperate.Delete);
        }

        private bool Operate(List<Ps> list, ref string _errmsg, DataOperate operate)
        {
            string strSQL = "";
            switch (operate)
            {
                case DataOperate.Insert:
                    strSQL = SQL_INSERT;
                    break;
                case DataOperate.Update:
                    strSQL = SQL_UPDATE;
                    break;
                case DataOperate.Delete:
                    strSQL = SQL_DELETE;
                    break;
            }
            bool bRet = false;
            List<MySqlParameter[]> parms = new List<MySqlParameter[]>();
            MySqlParameter childparms = null;
            foreach (var item in list)
            {
                List<MySqlParameter> tempParm = new List<MySqlParameter>();
                foreach (KeyValuePair<string, string> child in item)
                {
                    childparms = new MySqlParameter(child.Key, child.Value);
                    tempParm.Add(childparms);
                }
                parms.Add(tempParm.ToArray());
            }
            bRet = MySQL.MySQLHelper2.ExecuteListCmd(strSQL, parms, ref _errmsg);
            return bRet;
        }
    }
}
